import pygame
import sys
import direction

class InputHandler:
	def __init__ (self):
		self.inputOrderStack = []
		self.playerKeySubscribers = []
		self.currentDirection = direction.Stopped

	def Update (self, events):
		for event in events:
			if event.type == pygame.QUIT: 
				sys.exit()
				
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_DOWN:
					self.inputOrderStack.append(direction.Down)
					self.currentDirection = direction.Down
				elif event.key == pygame.K_UP:
					self.inputOrderStack.append(direction.Up)
					self.currentDirection = direction.Up
				elif event.key == pygame.K_LEFT:
					self.inputOrderStack.append(direction.Left)
					self.currentDirection = direction.Left
				elif event.key == pygame.K_RIGHT:
					self.inputOrderStack.append(direction.Right)
					self.currentDirection = direction.Right
					
			if event.type == pygame.KEYUP:
				if event.key == pygame.K_DOWN:
					self.inputOrderStack.remove(direction.Down)
				elif event.key == pygame.K_UP:
					self.inputOrderStack.remove(direction.Up)
				elif event.key == pygame.K_LEFT:
					self.inputOrderStack.remove(direction.Left)
				elif event.key == pygame.K_RIGHT:
					self.inputOrderStack.remove(direction.Right)
			if self.inputOrderStack == []:
				self.currentDirection = direction.Stopped

			elif self.currentDirection != self.inputOrderStack[-1]:
				self.currentDirection = self.inputOrderStack[-1]
		
		for subscriber in self.playerKeySubscribers:
			subscriber(self.currentDirection)



	